<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
     <!-- <el-form-item label="生产计划id" prop="stockProductionPlanId">
        <el-input
          v-model="queryParams.stockProductionPlanId"
          placeholder="请输入生产计划id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
     <!-- <el-form-item label="实际生产数量" prop="stockProductionCount">
        <el-input
          v-model="queryParams.stockProductionCount"
          placeholder="请输入实际生产数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="生产日期" prop="stockProductionTime">
        <el-date-picker clearable
          v-model="queryParams.stockProductionTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择生产日期">
        </el-date-picker>
      </el-form-item>
    <!--  <el-form-item label="库存" prop="stockCount">
        <el-input
          v-model="queryParams.stockCount"
          placeholder="请输入库存"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
    <!--  <el-form-item label="负责人" prop="stockUserId">
        <el-input
          v-model="queryParams.stockUserId"
          placeholder="请输入负责人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="预制菜" prop="PremaidFoodId">
        <el-select
            v-model="queryParams['premaidFood.premaidFoodId']"
            placeholder="请选择预制菜"
            clearable
            style="width: 100%"
          >
          <el-option
            v-for="food in premaidFoodOptions"
            :key="food.premaidFoodId"
            :label="food.premaidFoodName"
            :value="food.premaidFoodId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="负责人" prop="stockUserId">
        <el-select
                  v-model="queryParams.stockUserId"
                  placeholder="请选择负责人"
                  clearable
                  style="width: 100%"
                >
          <el-option
            v-for="user in userOptions"
            :key="user.userId"
            :label="user.userName"
            :value="user.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:stock:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:stock:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:stock:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
         <el-button
           type="warning"
           plain
           icon="el-icon-close"
           size="mini"
           @click="handleClean"
           v-hasPermi="['system:stock:clean']"
         >清理库存</el-button>
       </el-col>
     <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:stock:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="stockList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="生产批次" align="center" prop="stockId" />
      <el-table-column label="预制菜名称" align="center" prop="premaidFood.premaidFoodName" />
      <!-- <el-table-column label="生产计划id" align="center" prop="stockProductionPlanId" /> -->
      <el-table-column label="实际生产数量" align="center" prop="stockProductionCount" />
      <el-table-column label="实际生产时间" align="center" prop="stockProductionTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.stockProductionTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="库存" align="center" prop="stockCount" />
      <!-- <el-table-column label="负责人" align="center" prop="stockUserId" /> -->
      <el-table-column label="负责人" align="center" prop="user.userName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:stock:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:stock:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改库存管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="生产计划" prop="stockProductionPlanId" v-if="title == '添加库存管理'">
          <el-select
            v-model="form.stockProductionPlanId"
            placeholder="请选择生产计划"
            filterable
            clearable
            @change="handlePlanChange"
            style="width: 100%"
          >
            <el-option
              v-for="plan in productionPlanOptions"
              :key="plan.prductionPlanId"
              :label="`${plan.prductionPlanId} (${plan.premaidFood && plan.premaidFood.premaidFoodName})`"
              :value="plan.prductionPlanId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="预制菜" prop="premaidFoodName" v-if="title == '添加库存管理'">
          <el-input v-model="form.premaidFood.premaidFoodName" disabled />
        </el-form-item>
        <el-form-item label="计划产量" prop="prductionPlanCount" v-if="title == '添加库存管理'">
          <el-input v-model="form.prductionPlanCount" disabled />
        </el-form-item>
        <el-form-item label="实际生产数量" prop="stockProductionCount" v-if="title == '添加库存管理'">
          <el-input v-model="form.stockProductionCount" placeholder="请输入实际生产数量" />
        </el-form-item>
        <el-form-item label="库存数量" prop="stockCount">
          <el-input v-model="form.stockCount"  />
        </el-form-item>
        <el-form-item label="负责人" prop="stockUserId">
          <el-select
            v-model="form.stockUserId"
            placeholder="请选择负责人"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="user in userOptions"
              :key="user.userId"
              :label="user.userName"
              :value="user.userId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  <!--  <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="生产计划id" prop="stockProductionPlanId">
          <el-input v-model="form.stockProductionPlanId" placeholder="请输入生产计划id" />
        </el-form-item>
        <el-form-item label="生产数量" prop="stockProductionCount">
          <el-input v-model="form.stockProductionCount" placeholder="请输入实际生产数量" />
        </el-form-item>
        <el-form-item label="生产时间" prop="stockProductionTime">
          <el-date-picker clearable
            v-model="form.stockProductionTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择实际生产时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="库存" prop="stockCount">
          <el-input v-model="form.stockCount" placeholder="请输入库存" />
        </el-form-item>
        <el-form-item label="负责人" prop="prductionPlanUserId">

          <el-select
                      v-model="form.prductionPlanUserId"
                      placeholder="请选择负责人"
                      clearable
                      style="width: 100%"
                    >
            <el-option
              v-for="user in userOptions"
              :key="user.userId"
              :label="user.userName"
              :value="user.userId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog> -->

  </div>
</template>

<script>
import { listStock, getStock, delStock, addStock, updateStock, cleStock } from "@/api/system/stock";
import {listUser} from "@/api/system/user"
import {listFood} from "@/api/system/food"
import {listPlan, getPlan} from "@/api/system/plan"

export default {
  name: "Stock",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库存管理表格数据
      stockList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        stockProductionPlanId: null,
        stockProductionCount: null,
        stockProductionTime: null,
        stockCount: null,
        stockUserId: null,
        user: {userName: null},
        'premaidFood.premaidFoodId':  null,
        'premaidFood.premaidFoodName': null
      },

      // 下拉选项数据
      premaidFoodOptions: [], // 预制菜选项
      userOptions: [],        // 负责人选项
      productionPlanOptions: [],    //生产计划选项

      // 表单参数
      form: {},
      // 表单校验
      rules: {
        stockProductionPlanId: [
          { required: true, message: "请选择生产计划", trigger: "change" }
        ],
        stockProductionCount: [
          { required: true, message: "请输入实际生产数量", trigger: "blur" },
          { pattern: /^[1-9]\d*$/, message: "请输入正整数" }
        ],
        stockCount: [
          { required: true, message: "请输入库存数量", trigger: "change" },
          { pattern: /^[0-9]\d*$/, message: "请输入非负数" }
        ],
        stockUserId: [
          { required: true, message: "请选择负责人", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.loadPremaidFoodOptions();
    this.loadUserOptions();
    this.loadProductionPlanOptions();
  },
  methods: {
    // 加载生产计划选项
    loadProductionPlanOptions() {
      listPlan({ prductionPlanStatic: 1 }) // 只查询计划生产的生产计划
        .then(response => {
          this.productionPlanOptions = response.rows;
        });
    },
    //加载预制菜下拉选项
    loadPremaidFoodOptions() {
      listFood().then(response => {
        this.premaidFoodOptions = response.rows;
      });
    },
    /** 加载负责人下拉选项 */
    loadUserOptions() {
      listUser().then(response => {
        this.userOptions = response.rows;
      });
    },
    // 生产计划选择变化时触发
    handlePlanChange(planId) {
      if (planId) {
        getPlan(planId).then(response => {
          const plan = response.data;
          this.form = {
            ...this.form,
            stockProductionPlanId: plan.prductionPlanId,
            prductionPlanCount: plan.prductionPlanCount,
            premaidFood: {
              premaidFoodId: plan.premaidFood.premaidFoodId,
              premaidFoodName: plan.premaidFood.premaidFoodName
            },
            stockProductionCount: plan.prductionPlanCount, // 默认等于计划产量
            stockCount: plan.prductionPlanCount, // 默认库存等于实际生产数量
            stockUserId: plan.prductionPlanUserId // 默认负责人为计划负责人
          };
        });
      } else {
        this.form.premaidFood = {};
        this.form.prductionPlanCount = null;
      }
    },
    /** 查询库存管理列表 */
    getList() {
      this.loading = true;
      listStock(this.queryParams).then(response => {
        this.stockList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        stockId: null,
        stockProductionPlanId: null,
        stockProductionCount: null,
        stockProductionTime: null,
        stockCount: null,
        stockUserId: null,
        premaidFood: {},
        user: {}
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.stockId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加库存管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const stockId = row.stockId || this.ids
      getStock(stockId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改库存管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.title === "添加库存管理") {
            const submitData = {
              stockProductionPlanId: this.form.stockProductionPlanId,
              stockProductionCount: this.form.stockProductionCount,
              stockCount: this.form.stockCount,
              stockUserId: this.form.stockUserId
            };
            addStock(submitData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          } else {
            const submitData = {
              stockId: this.form.stockId,
              stockCount: this.form.stockCount,
              stockUserId: this.form.stockUserId
            };
            updateStock(submitData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const stockIds = row.stockId || this.ids;
      this.$modal.confirm('是否确认删除生产批次号为"' + stockIds + '"的数据项？').then(function() {
        return delStock(stockIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 清理库存按钮操作 */
    handleClean(row) {
      const stockIds = row.stockId || this.ids;
      this.$modal.confirm('是否确认清理生产批次为"' + stockIds + '"的库存？').then(function() {
        return cleStock(stockIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("清理完成");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/stock/export', {
        ...this.queryParams
      }, `stock_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
